<!--
 * @Descripttion: unTitle
 * @Author: yizheng.yuan
 * @Date: 2021-10-28 11:56:55
 * @LastEditors: yizheng.yuan
 * @LastEditTime: 2021-11-05 09:33:43
-->
<template>
  <div class="wrapper">
    <div class="head">
      <div class="iconBox"><van-icon name="cross" /></div>
      <div class="head_main">投诉反馈</div>
      <div class="iconBox"><van-icon name="ellipsis" /></div>
    </div>
    <div class="bannerBox">
      <div class="bannner_img">
        <img src="../assets/images/ts_head.png" class="mid_img" />
      </div>
      <div class="banner_text">
        <span class="orange_color">投诉</span>事件
      </div>
      
    </div>

      <div class="row_lr mg-b10 pd-lr10">
        <div><van-icon name="apps-o" />事件类型</div>
        <div>投诉<van-icon name="arrow" /></div>
      </div>

      <div class="form1">
        <ul>
          <li v-for="(item,index) in formList" :key="item.name+index">
            <div class="row_title">
              <van-icon :name="item.icon" />
              {{item.displayName}}
              <i class="xing" v-if="item.require">*</i>
            </div>
            <van-number-keyboard
              v-model="form[item.name]"
              :show="showNum"
              @blur="showNum = false"
            />
            <van-field
            v-if="item.name === 'phone'"
              readonly
              clickable
              :value="form[item.name]"
              @touchstart.native.stop="showNum = true"
            />
            <input v-else class="row_input" :disabled="item.disabled" v-model="form[item.name]" />
          </li>
        </ul>
      </div>

      <div class="formOne">
        <div class="row_one border_b">
          <div class="row_h46">
            <van-icon name="pending-payment" />
            被投诉的单位或当事人
            <i class="xing">*</i>
            </div>
          <div class="row_h46">
            <input style="width:100%" class="row_input border_none"
            v-model="form.currentCompany"/>
          </div>
        </div>
        <div class="row_one">
          <div class="row_h46">
            <van-icon name="location-o" />
            事件地址</div>
          <div class="row_h46 posr">
            <input style="width:100%" class="row_input border_none"
             @click="getAddress"
              v-model="form.address" />
            <i class="iconfont icon-dingwei rightIcon"></i>
          </div>
        </div>
      </div>

      <div class="form3 mg-t10">
        <div class="row_h46 row_lr border_b">
          <div class="row_title">
            <van-icon name="search" />
            问题归类
          </div>
          <div class="flexBox-r">
            <div class="flex1">
              <van-field
                readonly
                clickable
                autosize
                input-align="right"
                :value="form.questionKind"
                placeholder="请选择"
                @click="showPicker = true"
                style="background-color:none;"
              />
            </div>
            <div class="row_h46"><van-icon name="arrow" /></div>
          </div>
        </div>
        <div class="row_h46 row_lr border_b">
          <div class="row_title">
            <van-icon name="newspaper-o" />
            问题细分
          </div>
          <div class="flexBox-r">
            <div class="flex1">
              <van-field
                readonly
                clickable
                autosize
                input-align="right"
                :value="form.questionDetail"
                placeholder="请选择"
                @click="showPicker1 = true"
                style="background-color:none;"
              />
            </div>
            <div class="row_h46"><van-icon name="arrow" /></div>
          </div>
        </div>
        <div class="row_h46 row_lr">
          <div class="row_title">
            <van-icon name="coupon-o" />
            事件所在区域
          </div>
          <div class="flexBox-r">
            <div class="flex1">
              <van-field
                v-model="form.happenArea"
                is-link
                readonly
                input-align="right"
                placeholder="请选择所在地区"
                @click="showPicker2 = true"
              />
            </div>
            <div class="row_h46"><van-icon name="arrow" /></div>
          </div>
        </div>
      </div>

      <div class="form3 mg-t10 over_hide">
        <div class="row_h46">
          <van-icon name="newspaper-o" />
          事件内容
        </div>
        <div style="height:120px">
          <textarea rows="5" v-model="form.content" class="text_a" />
        </div>
      </div>

      <div class="btn_box">
        <button  class="sub_btn" @click="sureFun">确定提交</button>
      </div>

      <!-- 底部弹出框 -->

      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="kindArr"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        />
      </van-popup>
      <van-popup v-model="showPicker1" round position="bottom">
        <van-picker
          show-toolbar
          :columns="subKindArr"
          @cancel="showPicker1 = false"
          @confirm="onConfirm1"
        />
      </van-popup>
      <van-popup v-model="showPicker2" round position="bottom">
        <van-cascader
          v-model="form.happenArea"
          title="请选择所在地区"
          :options="areaArr"
          @close="showPicker2 = false"
          @finish="onFinish"
        />
      </van-popup>
      
      <!-- 定位组件 -->
      <iframe id="geoPage" width=0 height=0 frameborder=0  style="display:none;" scrolling="no"
          src="https://apis.map.qq.com/tools/geolocation?key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp">
      </iframe>
  </div>
</template>

<script>
import { Toast } from 'vant';

import Util from '../js/utils';
console.log('Util',Util);

import {mapState} from 'vuex';
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  data(){
    return{
      showPicker: false,
      showPicker1: false,
      showPicker2: false,
      areaArr: [],
      kindArr: [],
      subKindArr: [],
      showNum: false,
      requireArr: [
        {
          name: 'currentCompany',
          displayName: '被投诉的单位或当事人'
        }
      ],
      form:{
        date: '',
        personName: '',
        phone: '',
        address: '',
        currentCompany: '',
        questionKind: '',
        questionDetail: '',
        happenArea: '',
        content: ''
      },
      formList: [
        {
          icon: 'calendar-o',
          name: 'date',
          require: false,
          displayName: '事件日期',
          value: '',
          disabled: true
        },
        {
          icon: 'manager-o',
          name: 'personName',
          require: true,
          displayName: '投诉人姓名',
          value: '',
          disabled: false
        },
        {
          icon: 'phone-o',
          name: 'phone',
          require: true,
          displayName: '联系方式',
          value: '',
          disabled: false
        }
      ]
    }
  },
  computed:{
    ...mapState(['addressObj','tsForm'])
  },
  async mounted(){
    const that = this;
    // 如果tsForm存在，就回填数据
    if(this.tsForm){
      for(let key in this.tsForm){
        this.form[key] = this.tsForm[key]
      }
    }
    console.log('this.addressObj',this.addressObj);
    this.form.date = Util.formatDate(Date.now());
    if(this.addressObj && this.addressObj.poiaddress){
      this.form.address = this.addressObj.poiaddress;
    }
    // 腾讯地图定位: 选点组件和定位组件
    // https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation
    window.addEventListener('message', function(event) {
        // 接收位置信息
        var loc = event.data;
        console.error('腾讯地图定位：', loc);
        if(loc && loc.province && !that.addressObj.poiaddress){
          that.form.address = loc.addr ? loc.addr : loc.province+loc.city+loc.district;
          // that.form.address = JSON.stringify(loc)
          // alert(JSON.stringify(loc))
        }
    }, false);

    // 百度地图定位
    // if(!window.BMap){
    //   await this.MP();
    //   this.getCity();
    // }
    
    this.Login()

    this.getArea()
    this.getKind()
    
    setTimeout(()=>{
      let arr = document.getElementsByClassName('van-cell__right-icon');
      for (let i = 0; i < arr.length; i++) {
        arr[i].style.display = 'none';
      }
    })
  },
  methods:{
    async Login(){
      try {
        const url = '/sys/user/loginTest?loginName=admin&password=qiaolian@888'
        let rel = await Util.getData({
          url: `${window.baseUrl}${url}`,
          data: '',
          that: this
        })
        console.log('Login--1:',rel);
        console.error('this.$axios.headers',this.$axios.headers);
        let data = rel.data.data;
        if(data){
          // 设置cookie
          Util.cookieSet('token',data, Date.now()+3600*1000)
        }
      } catch (error) {
        console.error('Login-err',error);
      }
    },
    async getArea(){
      try {
        let rel = await Util.getData({
          url: `${window.baseUrl}/sys/area/tree?pageNo=1`,
          data: '',
          that: this
        })
        console.log('区域接口:',rel);
        if(rel.data.data){
          this.dealData(rel.data.data)
        }
      } catch (error) {
        console.error('err',error);
      }
    },
    dealData(arr){
      console.log('dealData',arr);
      let newArr=[];
      for (let i = 0; i < arr.length; i++) {
        arr[i].text=arr[i].name;
        arr[i].value=arr[i].name;
        let newOne = Object.assign({},arr[i])
        newArr.push(newOne)
        console.log('newOne',i,newOne);
        if(newOne.childrenList){
          newOne.children = [...newOne.childrenList]
          delete newOne.childrenList;
          this.loopEditSon(newOne.children)
        }
      }
      this.areaArr = newArr;
      console.log('最后arr',newArr);
    },
    loopEditSon(arr){
      for (let i = 0; i < arr.length; i++) {
        arr[i].text=arr[i].name;
        arr[i].value=arr[i].name;
        if(arr[i] && arr[i].childrenList && arr[i].childrenList.length>0){
          arr[i].children = [...arr[i].childrenList]
          delete arr[i].childrenList;
          this.loopEditSon(arr[i].children)
        }
      }
    },
    async getKind(){
      try {
        let rel = await Util.getData({
          url: `${window.baseUrl}/complaintProblemTypeOne/getPageList`,
          data: '',
          that: this
        })
        console.log('大类:',rel);
        const arr = rel.data.data;
        if(arr){
          for (let i = 0; i < arr.length; i++) {
            this.kindArr.push(arr[i].type)
          }
        }
      } catch (error) {
        console.error('err2',error);
      }
    },
    
    async getSubKind(){
      try {
        let rel = await Util.getData({
          url: `${window.baseUrl}/complaintProblemTypeTwo/getListByOne?oneType=${this.form.questionKind}`,
          data: '',
          that: this
        })
        console.log('细分:',rel);
        const arr = rel.data.data;
        if(arr){
          for (let i = 0; i < arr.length; i++) {
            this.subKindArr.push(arr[i].type)
          }
        }
      } catch (error) {
        console.error('err3',error);
      }
    },
    onConfirm(value) {
      this.form.questionKind = value;
      this.showPicker = false;
      this.getSubKind()
    },
    onConfirm1(value) {
      this.form.questionDetail = value;
      this.showPicker1 = false;
    },
    onFinish({ selectedOptions }) {
      this.showPicker2 = false;
      console.log('selectedOptions',selectedOptions);
      this.form.happenArea = selectedOptions.map((option) => option.text).join('/');
    },
    getAddress(){
      // 跳转之前要保存已写数据到vuex里面
      this.$store.commit('updateForm',Object.assign({},this.form))
      this.$router.push({
        path: '/map'
      })
    },
    sureFun(){
      // 检查必填输入框情况，未填则不允许提交
      let hasError='';
      for (let i = 0; i < this.formList.length; i++) {
        let one = this.formList[i];
        if(one.require){
          if(!this.form[one.name]){
            hasError=`${one.displayName} 不能为空！`;
            break;
          }
          if(one.name=='phone' && !Util.isPhone(this.form[one.name])){
            hasError=`${one.displayName} 格式不正确！`;
            break;
          }
        }
      }
      if(hasError){
        Toast(hasError)
        return
      }else{
        for (let i = 0; i < this.requireArr.length; i++) {
          let one = this.requireArr[i];
          if(!this.form[one.name]){
            hasError=one.displayName;
            break;
          }
        }
      }
      if(hasError){
        Toast(`${hasError} 不能为空！`)
        return
      }
      const obj={
        finishTime: this.form.date,
        complaintPerson: this.form.personName,
        contact: this.form.phone,
        enterprise: this.form.currentCompany,
        address: this.form.address,
        problemOne: this.form.questionKind,
        problemTwo: this.form.questionDetail,
        area: this.form.happenArea,
        incomingContent: this.form.content,

        deadTime: '',
        incomingTime: this.form.date,
        incomingType: "投诉",
        informationType: "测试来源",
        step: 2,
        suggestion: '',

        recordPerson: '',
        recordDept: '',
        recordNumber: '',
        record: '',
        emergencyType: '',
        secrecy: '',
        reply: '',
        dept: '',
        leader: '',
        instructTime: '',
        instruction: '',
        result: '',
        state: 2,
        stateEx: '',
        okTime: '',
        document: '',
        operator: ''
      }
      let url = `${window.baseUrl}/complaintRecord/insert`
      console.log('提交');
      // Toast('提交成功！');
      // qs.stringify(this.form)
      // url = '/api/aaa'
      this.$axios.post(url, obj
      )
      .then((res)=>{
        console.log('res',res);
        let ret = res.data;
        if(ret.status=='fail'){
          Toast(`提交失败：${ret.data.errMsg}`)
        }else{
          Toast('提交成功！')
        }
      })
      .catch(err=>{
        console.log('err',err);
        Toast('提交失败！')
      })
    },
    MP(ak='NmfCIrNZD29GgyaKXBR5awpIm15XVAGP') {
      return new Promise(((resolve, reject) => {
        if (!window.BMap) {
          const script = document.createElement('script');
          script.type = 'text/javascript';
          script.src = `http://api.map.baidu.com/api?v=2.0&ak=${ak}&callback=init`;
          script.onerror = reject;
          document.head.appendChild(script);
          console.error('window.BMap', window.BMap);
          setTimeout(() => {
            resolve(window.BMap);
          }, 1000); // 这里延迟1秒是关键，要不显示不出来
        } else {
          resolve(window.BMap);
        }
      }));
    },
    getCity() {
      return new Promise((resolve,reject) => {
        const getLocation = new BMap.Geolocation();
        var _this = this;
        getLocation.getCurrentPosition(
          (position) => {
            // position中存放所有的定位数据
            console.log('position定位对象',position);
            // 这里获取的是城市和省
            let ad = position.address;
            // _this.address = province + city;
            _this.form.address = ad.province+ad.city+ad.district+ad.street+ad.street_number;
            resolve()
          }, 
          () => {
            _this.form.address = '定位失败!';
            reject()
          }, {provider: 'baidu'}
        );
      })
      // 原文链接：https://blog.csdn.net/Leo_DLi/article/details/111579091
    }
  }

};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .xing{
    color: red;
    position: relative;
    top: 0;
    left: 0;
    font-size: 16px;
  }
  
  .text_a{
    width: 100%;

    border: none;
    /* height: 120px; */
    /* background-color: #ddd; */

  }
  .form3{
    padding: 0 10px;
    background-color: #fff;
    overflow: hidden;
  }
  .row_h46{
    height: 46px;
    line-height: 46px;
    text-align: left;
  }
  .border_none{
    border: none;
  }
  .border_b{
    border-bottom: 1px solid #ddd;
  }
  .formOne{
    text-align: left;
    background-color: #fff;
    padding: 0 10px;
    margin-top: 10px;
  }
  .wrapper{
    height: 100vh;
    width: 100vw;
    background-color: #f4f4f4;
  }
  .head{
    display: flex;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #ddd;
    text-align: center;
    
  }
  .bannner_img{
    height: 150px;
  }
  .bannner_img img{
    height: 100%;
  }
  .head_main{
    flex: 1;
    font-size: 14px;
    font-weight: bold;
  }
  .iconBox{
    margin: 0 10px;
  }
  .bannerBox{
    height: 200px;
    display: flex;
    flex-direction: column;
    background-image: linear-gradient(#303d9c, #1951b4);
  }
  
  .banner_text{
    height: 50px;
    line-height: 50px;
    font-size: 18px;
    color: #fff;
  }
  .orange_color{
    color: #e39e62;
  }


  .form1 ul{
    background-color: #fff;
    padding: 0 10px;
  }
  .form1 li{
    display: flex;
    height: 46px;
    line-height: 46px;
    border-bottom: 1px solid #ddd;
  }
  .form1 li:last-child{
    border:none;
  }
  .row_title{
    width: 150px;
    text-align: left;
  }
  .form1 li input{
    border: none;
  }
  .rightIcon{
    position: absolute;
    right: 5px;
    top: 5px;
    color: red;
  }
  .row_input{
    width: 100%;
    padding: 0 10px;
  }
</style>
